package com.sgb.kjwl.viewmodel.enterprise;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.enterprise.CopyrightEntity;
import com.sgb.kjwl.model.entity.enterprise.PatentDetailEntity;
import com.sgb.kjwl.model.entity.enterprise.TrademarkEntity;
import com.swgk.core.base.model.entity.ContactsEntitiy;
import com.swgk.core.base.model.entity.InvoicingInfoEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.util.UserOperating;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 创建资产交易订单
 */
public class CreateBuyMakeOverOrderViewModel extends AndroidViewModel {

    public MutableLiveData<String> ToastShow = new MutableLiveData<>();
    public MutableLiveData<Integer> showloading = new MutableLiveData<>();
    public MutableLiveData<List<ContactsEntitiy>> list_contancts = new MutableLiveData<>();
    public MutableLiveData<List<InvoicingInfoEntity>> list_recepiy = new MutableLiveData<>();
    public MutableLiveData<ContactsEntitiy> contancts = new MutableLiveData<>();
    public MutableLiveData<InvoicingInfoEntity> recepiydata = new MutableLiveData<>();
    public MutableLiveData<Boolean> show_cnotans_more = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> show_recepist_more = new MutableLiveData<>(false);
    public MutableLiveData<String> content = new MutableLiveData<>();
    public CopyrightEntity copyrightEntity;
    public TrademarkEntity trademarkEntity;
    public PatentDetailEntity patentDetailEntity;
    public String detailType = "";
    public String sellerPhone = "";
    public ContactsEntitiy linkdata = null;


    public String orderid;
    public long id;


    public MutableLiveData<String> message = new MutableLiveData<>();

    public CreateBuyMakeOverOrderViewModel(@NonNull @NotNull Application application) {
        super(application);
    }


    /**
     * 获取联系人列表1条
     */
    public void getContanctsList() {
        showloading.postValue(1);
        NewAPIManager.getInstance().getEnterPrisenewAPI().getContaactList(
                1,
                1,
                UserOperating.getInstance().isCompany() ? 1 : UserOperating.getInstance().isTeam() ? 2 : 0,
                SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""),
                SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, ""),
                SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, "")).enqueue(new Callback<BaseEntity<ListResponse<List<ContactsEntitiy>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<ContactsEntitiy>>>> call, Response<BaseEntity<ListResponse<List<ContactsEntitiy>>>> response) {
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData().getList() != null) {
                        list_contancts.postValue(response.body().getData().getList());
                    }
                } else {
                    list_contancts.postValue(new ArrayList<>());
                    ToastShow.postValue(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<ContactsEntitiy>>>> call, Throwable t) {
                ToastShow.postValue(t.getMessage());
            }
        });
    }



    /**
     * 获取开票列表1条
     */
    public void getReceiptList() {

        Call<BaseEntity<ListResponse<List<InvoicingInfoEntity>>>> call = UserOperating.getInstance().isCompany() ? NewAPIManager.getInstance().getEnterPrisenewAPI().getVerificationCode_company(1, 1) : NewAPIManager.getInstance().getEnterPrisenewAPI().getVerificationCode_team(1, 1);
        call.enqueue(new Callback<BaseEntity<ListResponse<List<InvoicingInfoEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<InvoicingInfoEntity>>>> call, Response<BaseEntity<ListResponse<List<InvoicingInfoEntity>>>> response) {
                showloading.postValue(2);
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData().getList() != null) {
                        list_recepiy.postValue(response.body().getData().getList());
                    }
                } else {
                    list_recepiy.postValue(new ArrayList<>());
//                    ToastShow.postValue(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<InvoicingInfoEntity>>>> call, Throwable t) {
                showloading.postValue(2);
                ToastShow.postValue(t.getMessage());
            }
        });
    }




    /**
     * 提交订单
     */
    public void submitMakeOverOrder() {


        if (linkdata == null) {
            ToastShow.postValue("请提交联系人信息");
            return;
        }
        if (recepiydata.getValue() == null||TextUtils.isEmpty(recepiydata.getValue().getCompanyName())) {
            ToastShow.postValue("请提交开票信息");
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        switch (detailType) {
            case "商标":
                map.put("transferPrice", trademarkEntity.getPrice());//转让价格
                map.put("dealPrice", trademarkEntity.getPrice());//成交价格
                map.put("sellerNo", trademarkEntity.getPublishType() == 1 ? trademarkEntity.getCompanyNo() : trademarkEntity.getPublishType() == 2 ? trademarkEntity.getTeamNo() : trademarkEntity.getCreateUser());
                map.put("sellerName", trademarkEntity.getPublishType() == 1 ? trademarkEntity.getCompanyName() : trademarkEntity.getPublishType() == 2 ? trademarkEntity.getRealName() : trademarkEntity.getRealName());
                map.put("detailsId", trademarkEntity.getId());//转让或服务详情唯一表示id
                map.put("publishType", trademarkEntity.getPublishType());
                map.put("agentNo", trademarkEntity.getCreateUser());
                map.put("agent", trademarkEntity.getRealName());
                map.put("orderType", 1);//订单类型 1表示商标转让 2表示专利转让
                break;

            case "版权":
                map.put("transferPrice", copyrightEntity.getPrice());//转让价格
                map.put("dealPrice", copyrightEntity.getPrice());//成交价格
                map.put("sellerNo", copyrightEntity.getPublishType() == 1 ? copyrightEntity.getCompanyNo() : copyrightEntity.getPublishType() == 2 ? copyrightEntity.getTeamNo() : copyrightEntity.getCreateUser());
                map.put("sellerName", copyrightEntity.getPublishType() == 1 ? copyrightEntity.getCompanyName() : copyrightEntity.getPublishType() == 2 ? copyrightEntity.getRealName() : copyrightEntity.getRealName());
                map.put("detailsId", copyrightEntity.getId());//转让或服务详情唯一表示id
                map.put("publishType", copyrightEntity.getPublishType());
                map.put("agentNo", copyrightEntity.getCreateUser());
                map.put("agent", copyrightEntity.getRealName());
                map.put("orderType", 3);//订单类型 1表示商标转让 2表示专利转让
                break;

            case "专利":
                map.put("transferPrice", patentDetailEntity.getPrice());//转让价格
                map.put("dealPrice", patentDetailEntity.getPrice());//成交价格
                map.put("sellerNo", patentDetailEntity.getPublishType() == 1 ? patentDetailEntity.getCompanyNo() : patentDetailEntity.getPublishType() == 2 ? patentDetailEntity.getTeamNo() : patentDetailEntity.getCreateUser());
                map.put("sellerName", patentDetailEntity.getPublishType() == 1 ? patentDetailEntity.getCompanyName() : patentDetailEntity.getPublishType() == 2 ? patentDetailEntity.getRealName() : patentDetailEntity.getRealName());
                map.put("detailsId", patentDetailEntity.getId());//转让或服务详情唯一表示id
                map.put("publishType", patentDetailEntity.getPublishType());
                map.put("agentNo", patentDetailEntity.getCreateUser());
                map.put("agent", patentDetailEntity.getRealName());
                map.put("orderType", 2);//订单类型 1表示商标转让 2表示专利转让
                break;
        }

        map.put("amount", 1);//数量  转让数量默认为1 服务数量待定
        map.put("orderClassification", 1);//1表示立即购买订单 2表示议价单
        map.put("termsPayment", 1);//付款方式 1表示在线支付
        map.put("comment", content.getValue());//备注
        map.put("buyersNo", UserOperating.getInstance().isPersonal() ? SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, "") : SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, ""));
        map.put("buyersName", UserOperating.getInstance().isPersonal() ? SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "") : SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME, ""));
        map.put("contactName", linkdata.getContactName());
        map.put("contactPhone", linkdata.getContactPhone());
        map.put("provinceCode", linkdata.getProvinceCode());
        map.put("provinceName", linkdata.getProvinceName());
        map.put("cityCode", linkdata.getCityCode());
        map.put("cityName", linkdata.getCityName());
        map.put("areaCode", linkdata.getAreaCode());
        map.put("areaName", linkdata.getAreaName());
        map.put("address", linkdata.getAddress());
        map.put("postCode", linkdata.getPostCode());
        map.put("companyName", linkdata.getCompanyName());
        map.put("position", linkdata.getPosition());
        map.put("invoiceId", recepiydata.getValue().getId());
        map.put("invoiceTitle", recepiydata.getValue().getCompanyName());
        map.put("number", recepiydata.getValue().getNumber());
        map.put("bank", recepiydata.getValue().getBank());
        map.put("bankAccount", recepiydata.getValue().getBankAccount());
        map.put("companyAddress", recepiydata.getValue().getAddress());
        map.put("tel", recepiydata.getValue().getTel());
        map.put("buyerPublishType", UserOperating.getInstance().isCompany() ? 1 : UserOperating.getInstance().isTeam() ? 2 : 0);
        map.put("buyerAgent", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, ""));
        map.put("buyerAgentNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""));
        map.put("contactId", linkdata.getId());
        map.put("contactStatus", linkdata.getStatus());
        //买家手机
        map.put("buyerPhone", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, ""));
        //卖家手机
        map.put("sellerPhone", sellerPhone);
        showloading.postValue(1);
        Log.e("message",new Gson().toJson(map));
        NewAPIManager.getInstance().getEnterPrisenewAPI().submitMakeOverOreder(
                map).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                showloading.postValue(2);
                if (response.body() == null ) {
                    return;
                }
                if ( response.body().getData() != null&&response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    try {
                        JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(response.body().getData()));
                        if(json.get("orderId")!=null){
                            orderid = json.getString("orderId");
                        }
                        if(json.get("id")!=null){
                            id = json.getLongValue("id");
                        }
                        message.postValue(APIManager.RESPONSE_OK);
                    }catch (Exception e){
                        e.printStackTrace();
                    }



                } else {
                    message.postValue(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                showloading.postValue(2);

//                message.postValue(t.getMessage());

            }
        });

    }
}
